package org.coding.springbootdemocommandline.relock;

import java.util.concurrent.locks.ReentrantLock;

public class InterruptiblyLock {
    public ReentrantLock lock1 = new ReentrantLock();
    public ReentrantLock lock2 = new ReentrantLock();

    public Thread thread1(){
        Thread t = new Thread(()->{
            try {
                //如果当前线程未被中断,则获取锁
                lock1.lockInterruptibly();
                //这里执行业务逻辑
                Thread.sleep(5000);
                lock2.lockInterruptibly();
                System.out.println(Thread.currentThread().getName() + ",执行完毕");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                //在业务逻辑执行结束后,检查当前线程是否持有该锁,如果持有则释放锁
                if(lock1.isHeldByCurrentThread()){
                    lock1.unlock();
                }
                if(lock2.isHeldByCurrentThread()){
                    lock2.isHeldByCurrentThread();
                }
                System.out.println(Thread.currentThread().getName()+",退出");
            }
        });
        t.start();
        return t;
    }

    public Thread thread2(){
        Thread t = new Thread(()->{
            try {
                lock2.lockInterruptibly();
                Thread.sleep(5000);
                lock1.lockInterruptibly();
                System.out.println(Thread.currentThread().getName()+",执行完毕");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally{
                if(lock1.isHeldByCurrentThread()){
                    lock1.unlock();
                }
                if(lock2.isHeldByCurrentThread()){
                    lock2.unlock();
                }
                System.out.println(Thread.currentThread().getName()+",退出");
            }
        });
        t.start();
        return t;
    }

    public static void main(String[] args) {
        long time = System.currentTimeMillis();
        InterruptiblyLock interruptiblyLock = new InterruptiblyLock();
        Thread t1 = interruptiblyLock.thread1();
        Thread t2 = interruptiblyLock.thread2();
        while(true){
            if(System.currentTimeMillis()-time >= 3000){
                t2.interrupt();
            }
        }
    }
}
